package com.sphd.beautysalon.activitys.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.SortInfo;
import com.sphd.beautysalon.interfaces.FoodListBuyNo;
import com.sphd.beautysalon.presenter.WaiterPresenterImpl;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.adapters.FoodListAdapter;
import com.sphd.beautysalon.adapters.TypeFoodAdapter;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.GreensInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.info.VipInfo;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.WaiterView;
import com.wzh.frame.utils.StringUtils;
import com.wzh.frame.views.ClearEditText;
import com.wzh.frame.views.RoundImageView;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 点餐界面
 */
public class WaiterAddOrdersActivity extends BaseActivity implements WaiterView, FoodListBuyNo {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_img)
    RoundImageView userImg;
    @BindView(R.id.user_card)
    TextView userCard;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.title)
    CardView title;
    @BindView(R.id.all_food_num)
    TextView allFoodNum;
    @BindView(R.id.all_food_money)
    TextView allFoodMoney;
    @BindView(R.id.next_btn)
    Button nextBtn;
    @BindView(R.id.buttom)
    CardView buttom;
    @BindView(R.id.type_food)
    ListView typeFood;
    @BindView(R.id.food_list)
    ListView foodList;
    Intent intent;
    Bundle bundle;
    RestaurantInfo restaurantInfo;
    LoginInfo loginInfo;
    WaiterPresenterImpl waiterPresenter;
    TypeFoodAdapter typeFoodAdapter;
    FoodListAdapter foodListAdapter;
    List<SortInfo> sortInfos;
    List<GreensInfo> greensInfos;
    private static final String TAG = "WaiterAddOrdersActivity";
    double allMoney = 0;
    int allNo = 0;
    VipInfo vipInfo;
    @BindView(R.id.ic_edit)
    ImageView icEdit;
    @BindView(R.id.content_waiter_add_orders)
    RelativeLayout contentWaiterAddOrders;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waiter_add_orders);
        addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        foodListAdapter.setFoodListBuyNo(this);
        typeFood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                typeFoodAdapter.setSelectItem(position);
                typeFoodAdapter.notifyDataSetChanged();
                for (int i = 0; i < greensInfos.size(); i++) {
                    if (greensInfos.get(i).getSortno().equals(sortInfos.get(position).getSortno())) {
                        foodList.setSelection(i);
                        break;
                    }
                }
            }
        });
        /*
        * list滚动 判断listView是否是手动
        * */
        foodList.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int scrollState;

            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                this.scrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    return;
                }
                Log.d("jiejie", "onScroll" + " firstVisibleItem" + firstVisibleItem + " visibleItemCount"
                        + visibleItemCount + " totalItemCount" + totalItemCount);

                for (int i = 0; i < sortInfos.size(); i++) {
                    if (greensInfos.get(firstVisibleItem).getSortno().equals(sortInfos.get(i).getSortno())) {
                        typeFood.setSelection(i);
                        typeFoodAdapter.setSelectItem(i);
                        typeFoodAdapter.notifyDataSetChanged();
                    }
                }


            }
        });
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        loginInfo = DataSupport.findLast(LoginInfo.class);
        waiterPresenter = new WaiterPresenterImpl(this);
        sortInfos = new ArrayList<>();
        greensInfos = new ArrayList<>();
        setTitleBar(toolbar, "下单");
        /*1、先判断是否是服务员 2、判断是否是超管 不是超管也不是服务员的 直接隐藏 是超管的判断是否*/
        // TODO: 2016/12/2

        if (!isWaiterCanDo(loginInfo,restaurantInfo)){
            icEdit.setVisibility(View.INVISIBLE);
            nextBtn.setVisibility(View.INVISIBLE);
        }
        initAdapter();
        addData();
    }





    private void initAdapter() {
        typeFoodAdapter = new TypeFoodAdapter(R.layout.item_type_food_order, sortInfos);
        typeFood.setAdapter(typeFoodAdapter);
        foodListAdapter = new FoodListAdapter(R.layout.item_food_list_order, greensInfos);
        foodList.setAdapter(foodListAdapter);
    }

    private void addData() {
        waiterPresenter.addData(RestaurantUrl.Httptitle
                + RestaurantUrl.ALLGREENS + "cgid=" + restaurantInfo.getId() + "&nw=0");
    }

    @Override
    public void recRes(List<SortInfo> sortInfosList, List<GreensInfo> greensList) {
        sortInfos.addAll(sortInfosList);
        typeFoodAdapter.notifyDataSetChanged();
        addType(greensList);
        foodListAdapter.notifyDataSetChanged();
    }

    /**
     * @param greensList 给菜品加分类头以及判断第一个菜属于什么菜品 然后选择对应的初始化分类
     */
    private void addType(List<GreensInfo> greensList) {
        for (int i = 0; i < sortInfos.size(); i++) {
            if (greensList.size() > 0) {
                for (int j = 0; j < greensList.size(); j++) {
                    if (sortInfos.get(i).getSortno().equals(greensList.get(j).getSortno())) {
                        greensList.get(j).setSort(sortInfos.get(i).getSort());
                        greensInfos.add(greensList.get(j));
                    }
                }
                if (greensList.get(0).getSortno().equals(sortInfos.get(i).getSortno())) {
                    typeFoodAdapter.setSelectItem(i);
                }
            }
        }
    }


    @OnClick({R.id.title, R.id.next_btn, R.id.ic_edit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title:
                showVipDialog();
                break;
            case R.id.next_btn:
                sureOrder();
                break;
            case R.id.ic_edit:
                    recordOrder();
                break;

        }
    }

    private void recordOrder() {
        intent.setClass(context,AddordersActivity.class);
        startActivity(intent);

    }

    private void sureOrder() {
        if (allNo <= 0) {
            toast("请选择菜品后下单");
        } else {
            bundle.putInt(Constant.ALLNO,allNo);
            bundle.putSerializable(Constant.GREENSINFO, (Serializable) confrimGreens(greensInfos));
            bundle.putSerializable(Constant.VIPINFO,vipInfo);
            intent.putExtras(bundle);
            intent.setClass(context,SureOrdersActivity.class);
            startActivity(intent);
        }
    }

    private void showVipDialog() {
        View view = getView(R.layout.layout_edittextdialog);
        ClearEditText clearEditText = (ClearEditText) view.findViewById(R.id.input);
        new AlertDialog.Builder(context).setTitle("请输入卡号或手机号码").setView(view).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (StringUtils.isEmpty(clearEditText.getText().toString())) {
                            toast("手机号码或卡号不能为空");
                        } else {
                            checkUser(clearEditText.getText().toString().trim());
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).show();
    }

    private void checkUser(String user) {
        waiterPresenter.getUserDate(RestaurantUrl.Httptitle + RestaurantUrl.ISVIP + "username=" + user +
                "&cgid=" + restaurantInfo.getId());
    }


    public List<?> test(int no, int itemsize, List<?> lists) {
        if (lists.size() != 0) {
            if ((int) lists.size() / 10 >= no) {
                List<Object> tempList = new ArrayList<Object>(lists.subList((no - 1) * itemsize, no * itemsize > lists.size() ?
                        (lists.size()) : no * itemsize));
                return tempList;
            }
        }
        return new ArrayList<Object>();
    }

    @Override
    public void itemPos(GreensInfo greensInfo) {
        int allNo = 0;
        for (SortInfo sortInfo : sortInfos) {
            if (sortInfo.getSortno().equals(greensInfo.getSortno())) {
                for (GreensInfo greensInfo1 : greensInfos) {
                    if (greensInfo.getSortno().equals(greensInfo1.getSortno())) {
                        allNo = allNo + greensInfo1.getBuyNo();
                    }
                }
                sortInfo.setAllNo(allNo);
                typeFoodAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void recUer(VipInfo vipInfo) {
        if (vipInfo != null) {
            userName.setText(StringUtils.isEmpty(vipInfo.getMem_name()) ? "无姓名" : vipInfo.getMem_name() + "\t积分" + vipInfo.getMem_integral() +
                    "\t余额" + vipInfo.getMem_account());
            userPhone.setText(vipInfo.getMem_phone());
            setImage(userImg, vipInfo.getMem_photo());
            userCard.setText(vipInfo.getMem_grade() == 0 ? "普通会员" : vipInfo.getMem_grade() == 1 ? "折扣会员" : "充值会员");
            this.vipInfo = vipInfo;
        }
    }

    @Override
    public void itemAdd(double money) {
        allNo++;
        allMoney = allMoney + money;
        allFoodNum.setText(allNo + "");

        allFoodMoney.setText(turn(allMoney, Constant.DECIMAL_POINT));
    }

    @Override
    public void itemSub(double money) {
        allNo--;
        allMoney = allMoney - money;
        allFoodNum.setText(allNo + "");
        allFoodMoney.setText(turn(allMoney, Constant.DECIMAL_POINT));
    }
    private List<GreensInfo> confrimGreens(List<GreensInfo> foodInfoList) {
        List<GreensInfo> infos = new ArrayList<>();
        for (int i = 0; i <foodInfoList.size(); i++) {
            if (foodInfoList.get(i).getBuyNo() != 0) {

                infos.add(foodInfoList.get(i));
            }
        }
        return infos;
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode==1){
//            addData();
//            vipInfo=null;
//            userName.setText("");
//            userPhone.setText("");
//            userImg.setImageResource(Integer.parseInt(null));
//            userCard.setText("绑定会员");
//        }
//    }
}
